<?php defined('_JEXEC') or die('Restricted access');
/**
 * @package             Joomla
 * @subpackage          CeltaWeb Traffic Component
 * @author              Steven Palmer
 * @author url          http://coalaweb.com
 * @author email        support@coalaweb.com
 * @license             GNU/GPL, see /files/en-GB.license.txt
 * @copyright           Copyright (c) 2012 Steven Palmer All rights reserved.
 * @version             Version 0.1.1 December 2012
 * 
 * The CeltaWeb traffic module was inspired by VCNT Thanks to Viktor Vogel {@link http://joomla-extensions.kubik-rubik.de/}
 * 
 * CeltaWeb Traffic is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class mod_celtawebtrafficHelper extends JObject
{

        public static function getIpAddress()
        {
            foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
                if (array_key_exists($key, $_SERVER) === true){
                    foreach (explode(',', $_SERVER[$key]) as $ip){
                        $ip = trim($ip); // just to be safe

                        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                        
                            return ($ip);
                        }
                    }
                }
            }
        }

	function count(&$params)
	{
                $config   = JFactory::getConfig();
                $siteOffset = $config->getValue('config.offset');
                $dtnow = JFactory::getDate('now', $siteOffset);
                $now = $dtnow->toUnix(true);

                $db	= JFactory::getDbo();

		$locktime 	=	$params->get('locktime', 60);
		$nobots		=	$params->get('nobots');
		$botslist	=	$params->get('botslist');
		$noip 		= 	$params->get('noip');
		$ipslist	= 	$params->get('ipslist');		
		$locktime	=	$locktime * 60;           

                if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '') {
                    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
                } else {
                    $ip = $_SERVER['REMOTE_ADDR'];
                }

		// Keep out bots
		$bot = 0;
                
		if ($nobots) 
		{
			if (isset($_SERVER['HTTP_USER_AGENT'])) 
			{
				$agent = $_SERVER['HTTP_USER_AGENT'];
				$bots_array =  explode(",", $botslist);
				foreach ( $bots_array as $e ) 
				{
					if (preg_match('/'.trim($e).'/i', $agent)) 
					{
						$bot = 1;
                                                break;
					}
				}
			} 
			else // Do not count if no user agent is transmitted
			{ 
				$bot = 1;
			}
		}
		
		// Lock out IP addresses
		$iplock = 0;
                
		if ($noip) 
		{
                    if (isset($_SERVER['REMOTE_ADDR'])||($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '') 
			{
                            if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '') {
                                $agent = $_SERVER['HTTP_X_FORWARDED_FOR'];
                            } else {
                                $agent = $_SERVER['REMOTE_ADDR'];
                            }
                            $ip_array = explode(",", $ipslist);
				foreach ($ip_array as $e) 
				{	
					if (preg_match('/'.trim($e).'/i', $agent)) 
					{
						$iplock = 1;
                                                break;
					}
				}
			} 
                    else // Do not lock if no IP is provided
			{ 
				$iplock = 1;
			}
		}
		
		
		// Check if IP already exists and reload lock expired
                
                $query = $db->getQuery(true);
                $query->select('count(*)');
                $query->from($db->quoteName('#__cwtraffic'));
                $query->where('ip = '. $db->quote($ip));
                $query->where('tm + '. $db->quote($locktime) .'>'. $db->quote($now));
                $db->setQuery($query);
                $items = $db->loadResult();
		
		// Call count, if conditions are met
		if (empty($items) AND ($bot == 0) AND ($iplock == 0)) 
		{
                    $query = $db->getQuery(true);
                    $query->insert($db->quoteName('#__cwtraffic'));
                    $query->columns('tm, ip');
                    $query->values($db->quote($now) . ',' . $db->quote($ip)); 
                    $db->setQuery($query);
                    $db->query();
			
		}
		return $query;
	}
	
	// Function - Reading Views
	function read(&$params)
	{
		$db	= JFactory::getDbo();

                $config   = JFactory::getConfig();
                $siteOffset = $config->getValue('config.offset');
                date_default_timezone_set($siteOffset);
              
		$day 			=	date('d');
		$month			=	date('m');
		$year			=	date('Y');
		$daystart		=	mktime(0,0,0,$month,$day,$year);
		$monthstart		=	mktime(0,0,0,$month,1,$year);
		$yesterdaystart         =	$daystart - (24*60*60);
                $weekstart              =       $daystart - ((date('N') - 1) * 24 * 60 * 60);
                $preset			= 	$params->get('preset', 0);
                

                //Count ongoing total
                $query = $db->getQuery(true);
                $query->select('TCOUNT');
                $query->from($db->quoteName('#__cwtraffic_total'));
                $db->setQuery($query);
                $tcount = $db->loadResult();
        
		// Create base to count from
                $query = $db->getQuery(true);
                $query->select('count(*)');
                $query->from($db->quoteName('#__cwtraffic'));
                $db->setQuery($query);
                $all_visitors = $db->loadResult();
                $all_visitors += $preset;
                $all_visitors += $tcount;
                
                //Todays Visitors
                $query = $db->getQuery(true);
                $query->select('count(*)');
                $query->from($db->quoteName('#__cwtraffic'));
                $query->where('tm > '. $db->quote($daystart));
                $db->setQuery($query);
                $today_visitors = $db->loadResult();
		
                //Yesterdays Visitors
                $query = $db->getQuery(true);
                $query->select('count(*)');
                $query->from($db->quoteName('#__cwtraffic'));
                $query->where('tm > '. $db->quote($yesterdaystart));
                $query->where('tm < '. $db->quote($daystart));
                $db->setQuery($query);
                $yesterday_visitors = $db->loadResult();
                
                //This Weeks Visitors
                $query = $db->getQuery(true);
                $query->select('count(*)');
                $query->from($db->quoteName('#__cwtraffic'));
                $query->where('tm >= '. $db->quote($weekstart));
                $db->setQuery($query);
                $week_visitors = $db->loadResult();
                
                //Months Visitors
                $query = $db->getQuery(true);
                $query->select('count(*)');
                $query->from($db->quoteName('#__cwtraffic'));
                $query->where('tm >= '. $db->quote($monthstart));
                $db->setQuery($query);
                $month_visitors = $db->loadResult();

		$ret = array($all_visitors, $today_visitors, $yesterday_visitors, $week_visitors, $month_visitors);
		return ($ret);
	}
	
            /**
            * Returns an array containing web visitor information
            *
            * @access public
            * @static
            * @return array
            *
            */
            
           public static function getBrowser()
            {
                $u_agent = $_SERVER['HTTP_USER_AGENT'];
                $bname = 'Unknown';
                $platform = 'Unknown';

                //First get the platform?
                if (preg_match('/linux/i', $u_agent)) {
                    $platform = 'Linux';
                }
                elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
                    $platform = 'Mac';
                }
                elseif (preg_match('/windows|win32/i', $u_agent)) {
                    $platform = 'Windows';
                }

                // Next get the name of the useragent yes seperately and for good reason
                if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
                {
                    $bname = 'IE';
                    $ub = "MSIE";
                }
                elseif(preg_match('/Firefox/i',$u_agent))
                {
                    $bname = 'Firefox';
                    $ub = "Firefox";
                }
                elseif(preg_match('/Chrome/i',$u_agent))
                {
                    $bname = 'Chrome';
                    $ub = "Chrome";
                }
                elseif(preg_match('/Safari/i',$u_agent))
                {
                    $bname = 'Safari';
                    $ub = "Safari";
                }
                elseif(preg_match('/Opera/i',$u_agent))
                {
                    $bname = 'Opera';
                    $ub = "Opera";
                }
                elseif(preg_match('/Netscape/i',$u_agent))
                {
                    $bname = 'Netscape';
                    $ub = "Netscape";
                }

                return array(
                    'userAgent' => $u_agent,
                    'name'      => $bname,
                    'platform'  => $platform,
                );
            }
            
        function clean(&$params)
            {
                $db	= JFactory::getDbo();
                
                $config   = JFactory::getConfig();
                $siteOffset = $config->getValue('config.offset');
                date_default_timezone_set($siteOffset);

                $month = date('m');
                $year = date('Y');
                $monthstart = mktime(0, 0, 0, $month, 1, $year);

                $cleanstart = $monthstart - (8 * 24 * 60 * 60);
                
                $query = $db->getQuery(true);
                $query->select('count(*)');
                $query->from($db->quoteName('#__cwtraffic'));
                $query->where('tm < '. $db->quote($cleanstart));
                $db->setQuery($query);
                $oldrows = $db->loadResult();

                if(!empty($oldrows))
                {    
                    $query = $db->getQuery(true);
                    $query->update($db->quoteName('#__cwtraffic_total'));
                    $query->set('tcount = tcount +' . $db->quote($oldrows)); 
                    $db->setQuery($query);
                    $db->query();
                    
                    $query = $db->getQuery(true);
                    $query->from($db->quoteName('#__cwtraffic'));
                    $query->delete();
                    $query->where('tm < '. $db->quote($cleanstart));
                    $db->setQuery($query);
                    $db->query();
                }

                return;
            }
}
